package com.hzk.encrypte.config;

import com.hzk.encrypte.annotation.EncrypteColumn;
import com.hzk.encrypte.annotation.EncrypteTable;
import com.hzk.encrypte.cache.MetaDataCache;
import com.hzk.encrypte.dto.EncrypteTableMetadata;
import com.hzk.encrypte.util.ScanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description
 * @Author hzk15
 * @Date 2022/3/29
 * @Verson 1.0
 **/
@Configuration
public class IntiTableCache implements InitializingBean {

    @Resource
    ScanUtils scanUtils;

    @Resource
    MetaDataCache metaDataCache;

    private static final Log log = LogFactory.getLog(IntiTableCache.class);

    @Override
    public void afterPropertiesSet() throws Exception {
        List<Class<?>> classes = scanUtils.scanEntityClasses(EncrypteTable.class);
        classes.forEach(item -> {
            log.info("======加载加密Table到缓存" + item.getName());
            Field[] declaredFields = item.getDeclaredFields();

            EncrypteTable tableAnno = item.getDeclaredAnnotation(EncrypteTable.class);

            List<String> columns = new ArrayList<>();
            for (Field declaredField : declaredFields) {
                EncrypteColumn columnAnno = declaredField.getDeclaredAnnotation(EncrypteColumn.class);
                if(Objects.nonNull(columnAnno)) {
                    log.info("======加载加密Column到缓存" + declaredField.getName());
                    columns.add(declaredField.getName());
                }
            }

            if(columns.size() > 0) {
                EncrypteTableMetadata metadata = new EncrypteTableMetadata(tableAnno.value(), columns);
                metaDataCache.put(tableAnno.value(), metadata);
            }

        });
    }
}
